//
//  LCWebViewController.m
//  码上用卡圈
//
//  Created by MAC on 2018/1/10.
//  Copyright © 2018年 congliu. All rights reserved.
//

#import "HWHomeWebViewController.h"
#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import "TGWebProgressLayer.h"
#import <DWKWebView.h>
#import "JsApiTest.h"

@interface HWHomeWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic,strong)DWKWebView *webView;

@property (nonatomic, strong)TGWebProgressLayer *webProgressLayer;  //加载进度条
@property (nonatomic, strong)NSMutableURLRequest *request;
@property (nonatomic, strong)NSString *flag;

@property (nonatomic, strong)UIImageView *bgImageView;//背景图
@property (nonatomic, strong)UIView *maskView;//蒙版
@property (nonatomic, strong)UIView *bgView;//
@property (nonatomic, strong)UIView *attentionBgView;//温馨提示
@end

@implementation HWHomeWebViewController

- (UIImageView *)bgImageView
{
    if (!_bgImageView)
    {
        _bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
        _bgImageView.image = [UIImage imageNamed:@"launch"];
    }
    return _bgImageView;
}

- (UIView *)maskView
{
    if (!_maskView)
    {
        _maskView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)];
        _maskView.backgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0 alpha:0.65];
    }
    return _maskView;
}

- (UIView *)attentionBgView
{
    if (!_attentionBgView)
    {
        _attentionBgView = [[UIView alloc] initWithFrame:CGRectMake(50*kUIScaleBasePlus,SCREEN_HEIGHT/2-115*kUIScaleBasePlus,SCREEN_WIDTH-100*kUIScaleBasePlus,230*kUIScaleBasePlus)];
        _attentionBgView.backgroundColor = [UIColor whiteColor];
        _attentionBgView.layer.masksToBounds = YES;
        _attentionBgView.layer.cornerRadius = 10;
        
        UILabel *titleLabel = [HWUtilties creatLabelWithFrame:CGRectMake(0,10*kUIScaleBasePlus,_bgView.frame.size.width,20*kUIScaleBasePlus)
                                                 textAligment:NSTextAlignmentCenter
                                                     textClor:LCHexColor(0x000000)
                                                     textFont:16*kUIScaleBasePlus];
        titleLabel.text = @"温馨提示";
        [_attentionBgView addSubview:titleLabel];
        
        UILabel *contextLabel = [HWUtilties creatLabelWithFrame:CGRectMake(10*kUIScaleBasePlus,CGRectGetMaxY(titleLabel.frame)+5*kUIScaleBasePlus,_bgView.frame.size.width-20*kUIScaleBasePlus,0)
                                                   textAligment:NSTextAlignmentLeft
                                                       textClor:LCHexColor(0x333333)
                                                       textFont:14*kUIScaleBasePlus];
        contextLabel.numberOfLines = 0;
        contextLabel.text = @"       根据国家相关法律规定，请您同意《嗨小说用户协议》和《嗨小说用户隐私保护政策》后开始使用我们的应用服务";
        [contextLabel sizeToFit];
        [_attentionBgView addSubview:contextLabel];
        
        UIButton *codingBtn = [HWUtilties creatButtonWithFrame:CGRectMake(10*kUIScaleBasePlus,CGRectGetMaxY(contextLabel.frame)+15*kUIScaleBasePlus,_bgView.frame.size.width-20*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                                  textAligment:NSTextAlignmentLeft
                                                          text:@"《嗨小说用户协议》"
                                                      textClor:JSAMainColor
                                                     buttonBGC:[UIColor clearColor]
                                                      textFont:14*kUIScaleBasePlus
                                                        target:self
                                                        method:@selector(haiwenConding)];
        [_attentionBgView addSubview:codingBtn];
        
        UIButton *privacyBtn = [HWUtilties creatButtonWithFrame:CGRectMake(10*kUIScaleBasePlus,CGRectGetMaxY(codingBtn.frame)+5*kUIScaleBasePlus,_bgView.frame.size.width-20*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                                   textAligment:NSTextAlignmentLeft
                                                           text:@"《嗨小说用户隐私保护政策》"
                                                       textClor:JSAMainColor
                                                      buttonBGC:[UIColor clearColor]
                                                       textFont:14*kUIScaleBasePlus
                                                         target:self
                                                         method:@selector(privacyClick)];
        [_attentionBgView addSubview:privacyBtn];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(privacyBtn.frame)+10*kUIScaleBasePlus, _bgView.frame.size.width,1*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [_attentionBgView addSubview:lineView];
        
        UIButton *agreeBtn = [HWUtilties creatButtonWithFrame:CGRectMake(0,CGRectGetMaxY(lineView.frame),_bgView.frame.size.width,40*kUIScaleBasePlus)
                                                 textAligment:NSTextAlignmentCenter
                                                         text:@"下一步"
                                                     textClor:JSAMainColor
                                                    buttonBGC:[UIColor clearColor]
                                                     textFont:16*kUIScaleBasePlus
                                                       target:self
                                                       method:@selector(netStep)];
        [_attentionBgView addSubview:agreeBtn];
        
    }
    return _attentionBgView;
}

- (UIView *)bgView
{
    if (!_bgView)
    {
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(50*kUIScaleBasePlus,SCREEN_HEIGHT/2-115*kUIScaleBasePlus,SCREEN_WIDTH-100*kUIScaleBasePlus,230*kUIScaleBasePlus)];
        _bgView.backgroundColor = [UIColor whiteColor];
        _bgView.layer.masksToBounds = YES;
        _bgView.layer.cornerRadius = 10;
        
        UILabel *titleLabel = [HWUtilties creatLabelWithFrame:CGRectMake(0,10*kUIScaleBasePlus,_bgView.frame.size.width,20*kUIScaleBasePlus)
                                                 textAligment:NSTextAlignmentCenter
                                                     textClor:LCHexColor(0x000000)
                                                     textFont:16*kUIScaleBasePlus];
        titleLabel.text = @"用户隐私保护提示";
        [_bgView addSubview:titleLabel];
        
        UILabel *contextLabel = [HWUtilties creatLabelWithFrame:CGRectMake(10*kUIScaleBasePlus,CGRectGetMaxY(titleLabel.frame)+5*kUIScaleBasePlus,_bgView.frame.size.width-20*kUIScaleBasePlus,0)
                                                   textAligment:NSTextAlignmentLeft
                                                       textClor:LCHexColor(0x333333)
                                                       textFont:14*kUIScaleBasePlus];
        contextLabel.numberOfLines = 0;
        contextLabel.text = @"       嗨小说为了更好的保护您的隐私和个人信息安全，根据国家相关规定和标准更新了《嗨小说用户协议》和《嗨小说用户隐私保护政策》，请你仔细阅读后并了解";
        [contextLabel sizeToFit];
        [_bgView addSubview:contextLabel];
        
        UIButton *codingBtn = [HWUtilties creatButtonWithFrame:CGRectMake(10*kUIScaleBasePlus,CGRectGetMaxY(contextLabel.frame)+15*kUIScaleBasePlus,_bgView.frame.size.width-20*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                                  textAligment:NSTextAlignmentLeft
                                                          text:@"《嗨小说用户协议》"
                                                      textClor:JSAMainColor
                                                     buttonBGC:[UIColor clearColor]
                                                      textFont:14*kUIScaleBasePlus
                                                        target:self
                                                        method:@selector(haiwenConding)];
        [_bgView addSubview:codingBtn];
        
        UIButton *privacyBtn = [HWUtilties creatButtonWithFrame:CGRectMake(10*kUIScaleBasePlus,CGRectGetMaxY(codingBtn.frame)+5*kUIScaleBasePlus,_bgView.frame.size.width-20*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                                   textAligment:NSTextAlignmentLeft
                                                           text:@"《嗨小说用户隐私保护政策》"
                                                       textClor:JSAMainColor
                                                      buttonBGC:[UIColor clearColor]
                                                       textFont:14*kUIScaleBasePlus
                                                         target:self
                                                         method:@selector(privacyClick)];
        [_bgView addSubview:privacyBtn];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(privacyBtn.frame)+10*kUIScaleBasePlus, _bgView.frame.size.width,1*kUIScaleBasePlus)];
        lineView.backgroundColor = JSALineColor;
        [_bgView addSubview:lineView];
        
        UIButton *cancelBtn = [HWUtilties creatButtonWithFrame:CGRectMake(0,CGRectGetMaxY(lineView.frame),_bgView.frame.size.width/2,40*kUIScaleBasePlus)
                                                  textAligment:NSTextAlignmentCenter
                                                          text:@"不同意"
                                                      textClor:LCHexColor(0x999999)
                                                     buttonBGC:[UIColor clearColor]
                                                      textFont:16*kUIScaleBasePlus
                                                        target:self
                                                        method:@selector(cancelClick)];
        [_bgView addSubview:cancelBtn];
        
        UIButton *agreeBtn = [HWUtilties creatButtonWithFrame:CGRectMake(CGRectGetMaxX(cancelBtn.frame),CGRectGetMaxY(lineView.frame),_bgView.frame.size.width/2,40*kUIScaleBasePlus)
                                                 textAligment:NSTextAlignmentLeft
                                                         text:@"同意"
                                                     textClor:JSAMainColor
                                                    buttonBGC:[UIColor clearColor]
                                                     textFont:16*kUIScaleBasePlus
                                                       target:self
                                                       method:@selector(agreeClick)];
        [_bgView addSubview:agreeBtn];
        
    }
    return _bgView;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setTitle:@"首页"];
    [HWUtilties alterUpDateApp];
    [self buryPoint];
    
    NSString *str = [kUserDefaults objectForKey:@"agreeUser"];
    if (str)
    {
        [self configSubView];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSString *str = [kUserDefaults objectForKey:@"agreeUser"];
    if (!str)
    {
        self.tabBarController.tabBar.hidden = YES;
        [self.view addSubview:self.bgImageView];
        [self.view addSubview:self.maskView];
        [self.view addSubview:self.bgView];
    }
    else
    {
        
        if (self.webView)
        {
            [self.webView removeFromSuperview];
            [self configSubView];
        }
        
        self.flag = @"";
    }
    

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeProgress];
}

#pragma 判断是返回首页还是返回
- (void)backAction
{
    if ([self.webView canGoBack])
    {
        [self.webView goBack];
    }else
    {
        [self.navigationController popViewControllerAnimated:false];
    }
}
#pragma 返回app
- (void)goHome
{
  [self.navigationController popViewControllerAnimated:false];
}

#pragma 配置子视图
- (void)configSubView
{
    
    self.webView = [self getCookieWebview];

    [self.view addSubview:self.webView];

}

//  注意，CookieWebview 和 正常的 webview 是不同的
- (DWKWebView *)getCookieWebview
{
    WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
    webConfig.userContentController = [[WKUserContentController alloc] init];
    webConfig.allowsInlineMediaPlayback = YES;
    // 设置偏好设置
    webConfig.preferences = [[WKPreferences alloc] init];
    // 默认为0
    webConfig.preferences.minimumFontSize = 10;
    // 默认认为YES
    webConfig.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示不能自动通过窗口打开
    webConfig.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    
    // web内容处理池
    webConfig.processPool = [[WKProcessPool alloc] init];
    // 将所有cookie以document.cookie = 'key=value';形式进行拼接
    NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = 'access_token=%@'; document.cookie = 'device=%@';",current_User.token,@"ios"];
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: cookieValue
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    [userContentController addUserScript:cookieScript];
    
    webConfig.userContentController = userContentController;
    
    _webView = [[DWKWebView alloc]initWithFrame:CGRectMake(0,NAVIBAR_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT-TABBAR_HEIGHT-TABBAR_HEIGHT-10*kUIScaleBasePlus) configuration:webConfig];
    _webView.navigationDelegate = self;

    self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:WEBCOMME_HOST]];
    
   [_webView loadRequest:self.request];
    
    [_webView addJavascriptObject:[[JsApiTest alloc]init] namespace:nil];
    
    return _webView;
}

//配置进度条
- (TGWebProgressLayer  *)webProgressLayer
{
    if (!_webProgressLayer)
    {
        _webProgressLayer = [[TGWebProgressLayer alloc] init];
        _webProgressLayer.frame = CGRectMake(0, NAVIBAR_HEIGHT - 2, WIDTH, 2);
        _webProgressLayer.strokeColor = kBtnOrange.CGColor;
        [self.navigationController.navigationBar.layer addSublayer:_webProgressLayer];
    }
    return _webProgressLayer;
}

- (void)removeProgress
{
    if (_webProgressLayer)
    {
        [_webProgressLayer tg_closeTimer]; 
        [_webProgressLayer removeFromSuperlayer];
        _webProgressLayer = nil;
    }
}

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [SVProgressHUD showWithStatus:@"加载中"];
    
//    __block NSInteger timeOut = 10;
//    WeakSelf(self)
//    //执行队列
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    //计时器 -》dispatch_source_set_timer自动生成
//    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
//    dispatch_source_set_event_handler(timer, ^{
//        if (timeOut <= 0)
//        {
//            if ([self.flag isEqualToString:@""])
//            {
//                dispatch_source_cancel(timer);
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
//                                                                                   message:@"网页加载过时"
//                                                                            preferredStyle:UIAlertControllerStyleAlert];
//                    
//                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"刷新" style:UIAlertActionStyleDefault
//                                                                          handler:^(UIAlertAction * action) {
//                                                                              [weakSelf.webView reload];
//                                                                              weakSelf.flag = @"";
//                                                                          }];
//                    [alert addAction:defaultAction];
//                    [self presentViewController:alert animated:YES completion:nil];
//                });
//            }
//            else
//            {
//                dispatch_source_cancel(timer);
//            }
//            
//        }
//        else
//        {
//            //开始计时
//            timeOut--;
//        }
//    });
//    
//    dispatch_resume(timer);
    
}

// 1. 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    BOOL isNavigator = YES;
    
    if (!isNavigator) {
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
   
}

// 4, 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    decisionHandler(WKNavigationResponsePolicyAllow);
    
}
// 8页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [_webProgressLayer tg_finishedLoadWithError:error];
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [SVProgressHUD dismiss];
    [_webProgressLayer tg_finishedLoadWithError:nil];
    
    WeakSelf(self)
    [_webView callHandler:@"indexFinished" completionHandler:^(id  _Nullable value) {
        weakSelf.flag = value;
    }];
    
    
}


- (void)dealloc
{
    [self removeProgress];
}


- (void)buryPoint
{
    NSString *jsonStr = [NSString stringWithFormat:@"{\"timestamp\":%@,\"toUrl\":\"/\",\"toId\":\"15327e3ab9640909\",\"dataType\":%@,\"network\":%@,\"softwareType\":%@,\"client\":%@,\"ipAddr\":\"%@\"}",[HWUtilties getNowTimeTimestamp3],@"1",@"1",@"3",@"3",[HWUtilties getIPAddress]];
    
    
    NSDictionary *prarmers = @{
                               @"jsonData" : jsonStr
                               };
    
    [PointManager haiBookShelfPoint:prarmers sucess:^(id  _Nonnull acceptData) {
        NSLog(@"首页埋点成功");
        NSDictionary *dic = [HWUtilties dictionaryWithJsonString:acceptData];
        HWBuryPointModel *model = [[HWBuryPointModel alloc]initWithDic:dic];
        [kUserDefaults setValue:model.timestamp.stringValue forKey:@"time"];
        [kUserDefaults synchronize];
    } fail:^(NSError * _Nullable error) {
        DISMISS_SVP(1.0f);
        [SVProgressHUD showErrorWithStatus:@"获取失败，请检查网络是否良好"];
        DISMISS_SVP(1.0f);
    }];
}


- (void)agreeClick
{
    [kUserDefaults setObject:@"1" forKey:@"agreeUser"];
    [kUserDefaults synchronize];
    
    [self.bgView removeFromSuperview];
    [self.maskView removeFromSuperview];
    [self.bgImageView removeFromSuperview];
    self.tabBarController.tabBar.hidden = NO;

    [self configSubView];

}

- (void)cancelClick
{
    [self.bgView removeFromSuperview];
    [self.view addSubview:self.attentionBgView];
    
}

- (void)netStep

{
    [self.attentionBgView removeFromSuperview];
    [self.view addSubview:self.bgView];
}

- (void)haiwenConding
{
    [HWUtilties pushWebWithUrl:[NSString stringWithFormat:@"%@%@",WEBCOMME_HOST,@"/userAgreement"] title:@"用户协议" toUrl:nil toId:nil];
}

- (void)privacyClick
{
    [HWUtilties pushWebWithUrl:[NSString stringWithFormat:@"%@%@",WEBCOMME_HOST,@"/privacyPolicy"] title:@"用户隐私政策" toUrl:nil toId:nil];
}
@end
